package com.imoocdl.controller;

import com.imoocdl.VO.ProductInfoVO;
import com.imoocdl.VO.ProductVO;
import com.imoocdl.VO.ResultVO;
import com.imoocdl.dataobject.ProductCategory;
import com.imoocdl.dataobject.ProductInfo;
import com.imoocdl.service.CategoryService;
import com.imoocdl.service.ProductService;
import com.imoocdl.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by pc on 2018/3/30.
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    @ResponseBody
    @Cacheable(cacheNames = "product",key = "123")
    public ResultVO list(){
        //1查询所有上架商品
       List<ProductInfo> productInfoList = productService.findUpAll();
       //2查询相关类目 (一次性查询)
        List<Integer> categoryList = new ArrayList<>();
        //传统方for循环
        //精简写法(java8特性    lambda表达式)
       List<Integer> categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());

        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
        //3数据瓶装
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory:productCategoryList) {
                ProductVO productVO= new ProductVO();
                productVO.setCategoryName(productCategory.getCategoryName());
                productVO.setCategoryType(productCategory.getCategoryType());


                List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo:productInfoList) {
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfo1 = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfo1);
                    productInfoVOList.add(productInfo1);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }

        return ResultVOUtil.success(productVOList);
    }
}
